<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
  {
    style: {
      navigationStyle: 'custom',
      // navigationBarTitleText: '',
    },
    anonymous: false
  }
</route>

<script lang="ts" setup>
import dayjs from 'dayjs'
import { useAppStore, useUserStore } from '@/stores'
import { ScheduleApi } from '@/apis'
import { loginRoute } from '@/interceptors/route'
// import Calendar from '@/components/Calendar/index.vue'
import ProgressBar from '@/components/ProgressBar/index.vue'

defineOptions({
  name: 'Home',
})

const userStore = useUserStore()

onShow(() => {
  if (!userStore.isLogin()) {
    uni.navigateTo({ url: loginRoute })
  }
})

const { statusBarHeight, navBarHeight } = useAppStore()

const today = dayjs().format('YYYY-MM-DD')
const selectedDate = ref(today)
const lessonList = ref<ScheduleApi.ScheduleLesson[]>([])
const lessonStat = reactive({
  totalLessonCount: 0,
  completedLessonCount: 0,
},
)
const lessonDateMap = ref<Record<string, ScheduleApi.ScheduleLesson[]>>({})
const lessonDateList = computed(() => Object.keys(lessonDateMap.value) || [])
const fullLessonDateList = computed(() => {
  return lessonDateList.value.filter(item => !lessonDateMap.value[item].some(lesson => lesson.totalCount === 0 || lesson.signInCount < lesson.totalCount))
})
const selectedDateLessonList = computed(() => (lessonDateMap.value[selectedDate.value] || []).sort((a, b) => a.startTime.localeCompare(b.startTime)))

// const notices = ref([])
// const getNoticeInfo = async () => {
//   // const res = await getNotice(userStore.userInfo?.id)
//   notices.value = []
// }

const getScheduleLessonList = async () => {
  const date = dayjs(selectedDate.value || today)
  const query: ScheduleApi.ScheduleLessonQuery = {
    lessonDateFrom: date.startOf('month').format('YYYY-MM-DD'),
    lessonDateTo: date.endOf('month').format('YYYY-MM-DD'),
  }
  lessonList.value = await ScheduleApi.getScheduleLessonList(query)

  lessonStat.totalLessonCount = lessonList.value.length
  lessonStat.completedLessonCount = 0
  lessonDateMap.value = {}
  for (const item of lessonList.value) {
    if (item.lessonStatus === 3) {
      lessonStat.completedLessonCount += 1
    }
    if (lessonDateMap.value[item.lessonDate]) {
      lessonDateMap.value[item.lessonDate].push(item)
    } else {
      lessonDateMap.value[item.lessonDate] = [item]
    }
    item.signInCount = item.signInCount || 0
    item.totalCount = item.totalCount || 0
  }
}

const onDateChange = (e) => {
  const selectedMonth = dayjs(selectedDate.value).format('YYYY-MM')
  selectedDate.value = e.fulldate
  if (selectedMonth !== dayjs(e.fulldate).format('YYYY-MM')) {
    getScheduleLessonList()
  }
}

const gotoLessonDetail = (item: ScheduleApi.ScheduleLesson) => {
  uni.navigateTo({
    url: `/pages/class/lesson?id=${item.id}`,
  })
}

const jump = (url: string) => {
  uni.navigateTo({ url })
}

onLoad(() => {
  getScheduleLessonList()
  // getNoticeInfo()
})
</script>

<template>
  <image class="background" mode="widthFix" src="/static/images/banner-bg.png" :draggable="false" />
  <view
    class="position-relative overflow-hidden px tab-page"
    :style="{ paddingTop: `${statusBarHeight}px`, zIndex: '1' }"
  >
    <view :style="{ height: `${navBarHeight}px` }" class="flex-row-start-center">
      <text class="logo-title z-1">
        秉烛未晚 学必有得
      </text>
    </view>

    <view class="my" style="height: 164rpx;">
      <image
        class="h-full w-full rounded-1" mode="aspectFill" src="/static/images/bingxue.jpeg"
        :draggable="false"
      />
    </view>

    <view class="box my flex-row-between-center py-[20rpx]">
      <view class="fun-item">
        <image src="/static/images/home/icon-1.png" class="fun-icon" />
        <text class="fun-text">
          我的服务
        </text>
      </view>
      <view class="fun-item" @click="jump('/pages/stat/index')">
        <image src="/static/images/home/icon-2.png" class="fun-icon" />
        <text class="fun-text">
          我的三率
        </text>
      </view>
      <view class="fun-item">
        <image src="/static/images/home/icon-3.png" class="fun-icon" />
        <text class="fun-text">
          续报助手
        </text>
      </view>
      <view class="fun-item">
        <image src="/static/images/home/icon-4.png" class="fun-icon" />
        <text class="fun-text">
          我的任务
        </text>
      </view>
      <view class="fun-item" @click="jump('/pages/index/parentRate')">
        <image src="/static/images/home/icon-5.png" class="fun-icon" />
        <text class="fun-text">
          家长评价
        </text>
      </view>
    </view>

    <!-- <view v-if="notices.length" class="my w-full">
      <wd-notice-bar :text="notices" background-color="#fff" color="#666">
        <template #prefix>
          <image
            src="/static/images/home/icon-notice.svg" mode="aspectFill"
            style="width: 44rpx;height: 44rpx;"
          />
        </template>
        <template #suffix>
          <wd-icon name="chevron-right" size="28rpx" />
        </template>
      </wd-notice-bar>
    </view> -->

    <view class="box">
      <!-- <Calendar :highlighted-dates="['2025-01-27', '2023-01-29']" /> -->
      <lx-calendar :value="selectedDate" :red-dot-dates="lessonDateList" :green-dot-dates="fullLessonDateList" :expanded="true" @change="onDateChange">
        <template #right>
          当月已上 {{ lessonStat.completedLessonCount }}/{{ lessonStat.totalLessonCount }}
        </template>
      </lx-calendar>
    </view>

    <view class="class-list pb-3 pt-1">
      <view
        v-for="(item, index) in selectedDateLessonList"
        :key="index"
        class="box mt-24rpx gap-16rpx px-32rpx py-24rpx"
      >
        <view class="mb-12px w-full flex-row-between-center">
          <view class="flex-row-start-center">
            <view class="text-44rpx font-500 text-main">
              {{ item.startTime }} - {{ item.endTime }}
            </view>
            <view class="ml-1">
              <wd-tag v-if="item.lessonStatus === 0" mark>
                停课
              </wd-tag>
              <wd-tag v-else-if="item.lessonStatus === 1 || item.lessonStatus === 2" color="#0083ff" bg-color="#d0e8ff" mark>
                待上课
              </wd-tag>
              <wd-tag v-else-if="item.lessonStatus === 3" type="primary" mark>
                已上课
              </wd-tag>
            </view>
          </view>

          <view class="">
            <wd-button type="text">
              {{ item.title }}
            </wd-button>
          </view>
        </view>
        <view class="flex-y gap-8px text-24rpx text-secondary">
          <view>
            {{ item.classInfo.name }}
          </view>
          <view>
            {{ item.campusName }}·{{ item.classroomName }}
          </view>
        </view>
        <view class="w-full flex-row-between-center">
          <view class="flex-1">
            <ProgressBar :text="`${item.signInCount}/${item.totalCount}`" :progress="item.signInCount * 100 / item.totalCount" />
          </view>
          <view class="ml-24rpx color-primary">
            <wd-button @click="gotoLessonDetail(item)">
              详情
            </wd-button>
          </view>
        </view>
      </view>
      <view v-if="!selectedDateLessonList.length" class="box mt-24rpx">
        <wd-status-tip image="content" tip="当日无课程安排" />
      </view>
    </view>
  </view>
</template>

<style scoped>
  .background {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 0;
    height: 564rpx;
  }

  .logo-title {
    font-size: 18px;
    font-weight: 500;
    line-height: 25.2px;
    text-align: center;
    background: linear-gradient(91.76deg, #13D085 -3.31%, #0A6A44 115.2%);
    background-clip: text;
    -webkit-background-clip: text;
    color: transparent;
  }

  :deep(.wd-notice-bar) {
    padding: 9px 20rpx !important;
  }

  .box {
    background: #fff;
    border-radius: 16rpx;
  }

  .fun-item {
    flex: 1;
    z-index: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .fun-icon {
    display: block;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 8rpx;
    width: 56rpx;
    height: 56rpx;
  }

  .fun-text {
    font-size: 24rpx;
    font-weight: 400;
    line-height: 22px;
    text-align: center;
    color: #1D2129;
  }

  .disabled view {
    color: #ccc !important;
  }
</style>
